package cn.dengta.webapp.trade.service;

import javax.annotation.Resource;

import cn.dengta.common.redis.RedisKeyLifetimeHelper;
import cn.dengta.context.model.RedisKey;
import cn.dengta.webapp.base.service.BaseServiceImpl;
import cn.dengta.webapp.trade.dao.PayRiskSmsLogDao;
import cn.dengta.webapp.trade.entity.PayRiskSmsLog;
import me.codeplayer.util.EasyDate;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 支付风控短信记录 服务实现类
 *
 * @author lizhichao
 * @since 2023-07-11
 */
@Service
public class PayRiskSmsLogService extends BaseServiceImpl<PayRiskSmsLog, PayRiskSmsLogDao, Long> {

	@Resource
	StringRedisTemplate stringRedisTemplate;
	final RedisKeyLifetimeHelper dayHolder = new RedisKeyLifetimeHelper();

	public void saveLog(Long userId, String phone) {
		PayRiskSmsLog log = new PayRiskSmsLog();
		log.setPhone(phone);
		log.setUserId(userId);
		save(log);
	}

	/**
	 * 检测风控短信发送时间
	 *
	 * @param userId 用户ID
	 * @return 是否通过
	 */
	public boolean checkSmsLimit(Long userId) {
		HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
		long now = System.currentTimeMillis();
		EasyDate d = new EasyDate(now);
		Long increment = hashOperations.increment(RedisKey.PAY_RISK_SMS_LIMIT, userId.toString(), 1);
		dayHolder.handleAfterOps(stringRedisTemplate, RedisKey.PAY_RISK_SMS_LIMIT, now, d);
		return increment <= 3;
	}

}
